<template>
  <div class="purchase-container">
    <!-- 页面标题与新增按钮 -->
    <div class="page-header">
      <h1 class="page-title">我的求购管理</h1>
      <el-button type="primary" size="large" :icon="Plus" @click="handleAddOpen">
        发布求购信息
      </el-button>
    </div>

    <!-- 列表区域 -->
    <div class="purchase-list" v-loading="tableLoading">
      <el-table
        :data="purchaseInfoList"
        stripe
        style="width: 100%; border-radius: 8px; overflow: hidden"
        :header-cell-style="{ background:'#f5f7fa',color:'#333',fontSize:'15px',fontWeight:600 }"
      >
        <el-table-column label="求购编号" prop="purchaseId" width="130" align="center" />
        <el-table-column label="设备类型" width="160" align="center">
          <template #default="scope">{{ scope.row.type?.typeName || '未知类型' }}</template>
        </el-table-column>
        <el-table-column label="品牌" prop="brand" width="120" align="center" />
        <el-table-column label="型号" prop="model" width="160" align="center" />
        <el-table-column label="期望价格(元)" width="160" align="center">
          <template #default="scope">{{ scope.row.expectedPrice?.toFixed(2) || '无' }}</template>
        </el-table-column>
        <el-table-column label="期望年份" prop="expectedYear" width="130" align="center" />
        <el-table-column label="联系人" prop="contactName" width="120" align="center" />
        <el-table-column label="联系电话" prop="contactPhone" width="150" align="center" />
        <el-table-column label="求购状态" width="140" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.purchaseStatus)">
              {{ getStatusText(scope.row.purchaseStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="200" align="center">
          <template #default="scope">{{ formatDate(scope.row.releaseTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="210" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              :icon="Edit"
              @click="handleEditOpen(scope.row)"
              :disabled="scope.row.purchaseStatus !== 0"
            >编辑</el-button>
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="handleDelete(scope.row.purchaseId)"
              :disabled="scope.row.purchaseStatus !== 0"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty
        v-if="purchaseInfoList.length === 0 && !tableLoading"
        description="暂无求购信息"
        class="empty-state"
      >
        <template #image>
          <img src="https://picsum.photos/seed/purchase/280/280" alt="无数据" class="empty-img" />
        </template>
      </el-empty>
    </div>

    <!-- 大气全屏弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      width="680px"
      top="8vh"
      align-center
      :close-on-click-modal="false"
      class="grand-dialog"
    >
      <template #title>
        <div class="dialog-head">
          {{ isEdit ? '编辑求购信息' : '发布求购信息' }}
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-position="top"
        class="grand-form"
      >
        <el-row :gutter="24">
          <el-col :md="12" :sm="24">
            <el-form-item label="设备类型" prop="typeId">
              <el-cascader
                v-model="cascaderValue"
                :options="allTypesList"
                :props="{ label:'typeName',value:'typeId',children:'children',checkStrictly:true }"
                placeholder="请选择设备类型"
                @change="handleTypeChange"
                :disabled="!allTypesList.length"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24">
            <el-form-item label="设备品牌" prop="brand">
              <el-input v-model="formData.brand" placeholder="请输入设备品牌（可选）" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :md="12" :sm="24">
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="formData.model" placeholder="请输入设备型号（可选）" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24">
            <el-form-item label="期望价格" prop="expectedPrice">
              <el-input
                v-model="formData.expectedPrice"
                placeholder="期望最高价格（元）"
                type="number"
                step="0.01"
                min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :md="12" :sm="24">
            <el-form-item label="期望年份" prop="expectedYear">
              <el-input
                v-model="formData.expectedYear"
                placeholder="期望设备年份（可选）"
                type="number"
                min="1990"
                :max="new Date().getFullYear()"
              />
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="formData.contactName" placeholder="联系人姓名" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :md="12" :sm="24">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="参数要求" prop="parameterRequirement">
          <el-input
            v-model="formData.parameterRequirement"
            placeholder="设备参数要求（可选）"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-foot">
          <el-button size="large" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" @click="handleSubmit">确认提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

/* ---------------- 状态变量 ---------------- */
const counterStore = useCounterStore()
const formRef = ref(null)
const dialogVisible = ref(false)
const isEdit = ref(false)
const tableLoading = ref(false)
const allTypesList = ref([])
const purchaseInfoList = ref([])
const cascaderValue = ref([])

const formData = ref({
  purchaseId: null,
  userId: null,
  typeId: null,
  brand: '',
  model: '',
  expectedPrice: null,
  expectedYear: null,
  parameterRequirement: '',
  contactName: '',
  contactPhone: '',
  businessmanId: null
})

const formRules = {
  typeId: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  expectedPrice: [{ required: true, message: '请输入期望价格', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
}

/* ---------------- 生命周期 ---------------- */
onMounted(() => {
  fetchAllTypes()
  fetchPurchaseInfoByUserId()
})

/* ---------------- 接口方法 ---------------- */
async function fetchAllTypes() {
  try {
    const res = await axios.get('/eduservice/equipmentType/getTypeTree')
    if (res.data?.success && Array.isArray(res.data.data?.typeTree)) {
      allTypesList.value = formatTreeData(res.data.data.typeTree)
    } else {
      allTypesList.value = []
      ElMessage.error('获取设备类型失败：数据格式异常')
    }
  } catch (e) {
    allTypesList.value = []
    ElMessage.error('网络异常，请稍后重试')
  }
}

async function fetchPurchaseInfoByUserId() {
  tableLoading.value = true
  try {
    const userId = counterStore.userId
    const res = await axios.get(`/eduservice/purchaseDemand/getPurchaseDemandByUserId/${userId}`)
    if (res.data?.success && Array.isArray(res.data.data?.purchaseDemandList)) {
      purchaseInfoList.value = res.data.data.purchaseDemandList
    } else {
      purchaseInfoList.value = []
    }
  } catch {
    purchaseInfoList.value = []
  } finally {
    tableLoading.value = false
  }
}

/* ---------------- 逻辑方法 ---------------- */
const formatTreeData = (data) =>
  Array.isArray(data)
    ? data.map((item) => ({
        ...item,
        children: formatTreeData(item.children || [])
      }))
    : []

const handleTypeChange = (val) => {
  formData.value.typeId = val?.length ? val[val.length - 1] : null
}

const handleAddOpen = () => {
  isEdit.value = false
  Object.assign(formData.value, {
    purchaseId: null,
    userId: counterStore.userId,
    typeId: null,
    brand: '',
    model: '',
    expectedPrice: null,
    expectedYear: null,
    parameterRequirement: '',
    contactName: '',
    contactPhone: '',
    businessmanId: null
  })
  cascaderValue.value = []
  nextTick(() => formRef.value?.resetFields())
  dialogVisible.value = true
}

/**
 * 根据叶子节点 id 递归查找祖先链
 */
function findPath(tree, id, path = []) {
  for (const node of tree) {
    const cur = [...path, node.typeId]
    if (node.typeId === id) return cur
    if (node.children?.length) {
      const target = findPath(node.children, id, cur)
      if (target) return target
    }
  }
  return null
}

const handleEditOpen = async (row) => {
  isEdit.value = true
  // 1. 回显普通字段
  Object.assign(formData.value, {
    purchaseId: row.purchaseId,
    userId: row.userId,
    typeId: row.typeId || null,
    brand: row.brand || '',
    model: row.model || '',
    expectedPrice: row.expectedPrice ? Number(row.expectedPrice) : null,
    expectedYear: row.expectedYear || null,
    parameterRequirement: row.parameterRequirement || '',
    contactName: row.contactName || '',
    contactPhone: row.contactPhone || '',
    businessmanId: row.businessmanId || null
  })

  // 2. 级联选择器需要完整路径
  if (row.typeId && allTypesList.value.length) {
    const path = findPath(allTypesList.value, row.typeId)
    cascaderValue.value = path || [row.typeId]
  } else {
    cascaderValue.value = []
  }

  // 3. 打开弹窗 & 清校验
  dialogVisible.value = true
  nextTick(() => formRef.value?.clearValidate())
}

async function handleSubmit() {
  await formRef.value.validate()
  const submitData = { ...formData.value }
  if (submitData.expectedPrice) submitData.expectedPrice = Number(submitData.expectedPrice)
  try {
    const res = isEdit.value
      ? await axios.post('/eduservice/purchaseDemand/updatePurchaseDemand', submitData)
      : await axios.post('/eduservice/purchaseDemand/addPurchaseDemand', submitData)
    if (res.data?.success) {
      ElMessage.success(isEdit.value ? '编辑成功' : '发布成功')
      dialogVisible.value = false
      fetchPurchaseInfoByUserId()
    } else {
      ElMessage.error(isEdit.value ? '编辑失败' : '发布失败')
    }
  } catch {
    ElMessage.error('提交失败，请稍后重试')
  }
}

async function handleDelete(purchaseId) {
  await ElMessageBox.confirm(
    `确定删除求购编号 ${purchaseId}？删除后无法恢复`,
    '删除确认',
    { type: 'warning' }
  )
  try {
    const res = await axios.delete(`/eduservice/purchaseDemand/deletePurchaseDemand/${purchaseId}`)
    if (res.data?.success) {
      ElMessage.success('删除成功')
      fetchPurchaseInfoByUserId()
    } else {
      ElMessage.error('删除失败')
    }
  } catch {
    ElMessage.error('网络异常，删除失败')
  }
}

/* ---------------- 工具函数 ---------------- */
const formatDate = (str) => {
  if (!str) return '暂无'
  const d = new Date(str)
  return isNaN(d.getTime())
    ? '无效时间'
    : d.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

const getStatusText = (s) =>
  ({ 0: '待处理', 1: '已分配', 2: '已成交', 3: '已取消' }[s] || '未知状态')

const getStatusTagType = (s) =>
  ({ 0: 'info', 1: 'success', 2: 'primary', 3: 'danger' }[s] || 'default')
</script>

<style scoped>
/* ---------- 页面通用 ---------- */
.purchase-container {
  padding: 32px;
  max-width: 1600px;
  margin: 0 auto;
  min-height: calc(100vh - 64px);
  background: #f5f7fa;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}
.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}
.purchase-list {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  padding: 24px;
}
.empty-state {
  padding: 80px 0;
}
.empty-img {
  width: 220px;
  height: 220px;
  border-radius: 50%;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* ---------- 全屏弹窗 ---------- */
.grand-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}
.dialog-head {
  height: 56px;
  line-height: 56px;
  text-align: center;
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  background: linear-gradient(90deg, #409eff 0%, #79bbff 100%);
}
.grand-form {
  padding: 24px 32px 8px;
}
.dialog-foot {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 16px 32px;
  background: #f5f7fa;
}
</style>